
#简单无向无权图的定义：用连接矩阵，不能有自环边(自己套自己)和平行边(两个顶点相互套)。
class graph:
    def __init__(self,file=None,v=None,e=None):
        self.fileName = file
        self.__GMatrix = None
        self.__V = v
        self.__E = e
    def createGraph(self):
        pass
    #下面是查看实列私有的属性，但是不能修改
    @property
    def getV(self):
        return self.__V
    @property
    def getE(self):
        return self.__E

    def __valid(self,v):
        '''
        :param v: int
        :return: 判断文件中顶点有效性
        '''
        if v<0 or v>self.__V:
            raise "顶点不存在"
        return
    def readGraph(self):
        '''
        :return: 读取文件中的关于图的信息，创建矩阵
        '''
        try:
            with open(self.fileName,"r") as f:
                s = f.readlines()#读取所有的行
                genRa = ( i.strip("\n").strip().replace(" ","",i.count(" ")) for i in s)#将一行中的换行符及空格去掉，方便我们取值
                ranges= next(genRa)
                self.__E = int(ranges[1])
                self.__V = int(ranges[0])
                if int(ranges[0])<=0 or int(ranges[1])<=0:
                    raise "顶点或边的数量不能少于零个"
                self.__GMatrix = [[0]*self.__V for _ in range(self.__V)]
                for _ in range(self.__E):
                    edges = next(genRa)
                    #这里还需要判断一下边的合法性：顶点的index必须小于顶点的总数且不能为零
                    a = int(edges[0])
                    b = int(edges[1])
                    self.__valid(a)
                    self.__valid(b)
                    if a==b:
                        raise "不能有环"
                    if self.__GMatrix[a][b]==1:
                        raise "不能有平行边"
                    self.__GMatrix[a][b]= 1
                    self.__GMatrix[b][a] = 1
            print(self.__GMatrix)
        except BaseException as e:
            print(e)
    def hasEdge(self,a,b):
        '''
        判断是否存在路径
        :return: bool
        '''
        if isinstance(a,int) and isinstance(b,int):
            if a<0 or b<0 or a>self.__V or b>self.__V:
                raise "顶点不存在"
            else:
                return self.__GMatrix[a][b]==1
        else:
            raise "顶点不合法"
    def adjacentVertices(self,v):
        adjV = []
        if isinstance(v,int):
            self.__valid(v)
            for index,val in enumerate(self.__GMatrix[v]):
                if val == 1:
                    adjV.append(index)
            else:
                return adjV
        else:
            raise "顶点不合法"
    def degree_of_vertic(self,v):
        return len(self.adjacentVertices(v))


if __name__ == '__main__':
    g = graph(r"D:\tensorflow2_pytorch\python算法\Graph\1.txt")
    g.readGraph()
    # print(g._graph__E)
    print(g.hasEdge(1, 6))
    print(g.adjacentVertices(1))
    print(g.degree_of_vertic(1))
